package com.example.fastjetpack.base.utils;

import android.util.Log;
import android.widget.Toast;

import com.example.fastjetpack.App;
import com.example.fastjetpack.data.ErrorMessage;
import com.google.gson.Gson;

import java.io.IOException;

import io.reactivex.functions.Consumer;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import retrofit2.Response;

public class ErrorHandler {
    private static final String TAG = "PUBLIC_ERROR_HANDLER";
    private static final Gson gson = new Gson();

    public static final Consumer<? super Throwable> TOAST_ERROR_HANDLER = throwable -> {
        String message = getErrorMessage(throwable);
        Throwable cause = throwable.getCause() == null ? throwable:throwable.getCause();
        Log.e(TAG,cause.getMessage());
        Toast.makeText(App.self, message, Toast.LENGTH_LONG).show();
    };

    public static String getErrorMessage(Throwable throwable) {
        String result = "发生错误";
        if (throwable.getCause() instanceof HttpException) {
            try {
                Response response = ((HttpException) throwable.getCause()).response();
                ResponseBody body = response.errorBody();
                String errorStr = body.string();
                ErrorMessage errorMessage = gson.fromJson(errorStr, ErrorMessage.class);
                result = errorMessage.getBody();
            } catch (IOException e) {
                Log.e(TAG,e.getMessage());
                return result;
            }
            return result;
        }else{
            return result;
        }
    }
}
